package com.netease.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.netease.domain.Commodity;
import com.netease.domain.ShoppingCart;
import com.netease.domain.User;
import com.netease.domain.User_Commodity;
import com.netease.service.CommodityService;
import com.netease.service.ShoppingcartService;
import com.netease.service.UserCommodityService;

/**
 * Servlet implementation class Ajax
 */
@WebServlet("/buy")
public class BuyServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5513349020099382181L;

	@Autowired
	private UserCommodityService usercommodityService;
	
	@Autowired
	private CommodityService commodityService;
	
	@Autowired
	private ShoppingcartService shoppingcartService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BuyServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		User user= (User) request.getSession().getAttribute("sys_user_key");
		List<ShoppingCart> shoppingcart_commodity = shoppingcartService.findAllByUserId(user.getId());
		try {
			boolean flag = true;
			String result = "";
			for(ShoppingCart sc:shoppingcart_commodity)
			{
				Commodity c = commodityService.findOne(sc.getCommodityId());
				if (c.getRemainningAmount()<sc.getAmount())
				{
					flag = false;
					result = result+"{"+sc.getTitle()+"}";
					continue;
					
				}
				User_Commodity uc = new User_Commodity();
				uc.setAmount(sc.getAmount());
				uc.setCommodityId(sc.getCommodityId());
				uc.setContent(sc.getContent());
				uc.setCreateTime(sc.getCreateTime());
				uc.setPicture(sc.getPicture());
				uc.setPrice(sc.getPrice());
				uc.setSummary(sc.getSummary());
				uc.setTitle(sc.getSummary());
				uc.setUser(sc.getUser());
				usercommodityService.save(uc);
				shoppingcartService.delete(sc.getId());
			}
			if (flag)
			{
				out.print("true");
			}
			else
			{
				out.print(result);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			out.print("false");
		}
		
		out.close();
	}

}

